<?php

namespace Home\Controller;

use Common\Controller\HomeBaseController;

/**
 * 商城首页Controller
 */
class IndexController extends HomeBaseController {
    /**
     * 首页
     */

    public function index() {

        $this->display();

    }

    public function canSubmit() {
        $set = M("other_set")->where("id=1")->find();
        $beganTime = $set['begantime'];
        $endtime = $set['endtime'];
        $json = array();
        $json['begantime'] = $beganTime;
        $json['endtime'] = $endtime;
        $json['canSubmit'] = checkCanSave();
        returnJson(true, $json);

    }

    public function Member() {

        $this->display();

    }

    public function getItemList() {
        $itemList = M("item")->join('canteen_item_class ON canteen_item_class.item_type_id = canteen_item.item_type')->where(array('canteen_item.status' => 1))->order('canteen_item_class.item_type_sort asc,canteen_item.item_sort asc')->select();

        $temp = array();
        foreach ($itemList as $k => $item) {
            //            $temp[intval($item['item_id'])] = $item;
            //            $temp[intval($item['item_id'])]['check'] = true;
            $itemList[$k]['check'] = false;
            $itemList[$k]['index'] = intval($item['item_id']);
            //            $itemList[$k]['index'] = $k;
            $itemList[$k]['memo'] = null;
            $itemList[$k]['show'] = true;
            $itemList[$k]['item_type'] = getItemTypeName($item['item_type']);
            $itemList[$k]['item_type_id'] = $item['item_type'];
            if (!$item['item_image']) {
                $itemList[$k]['item_image'] = 'null.jpg';
                $itemList[$k]['item_image_small'] = 'null.jpg';
            }
            else {
                $itemList[$k]['item_image_small'] = getSmallImage($item['item_image']);
            }
        }
        returnJson(true, $itemList);


    }

    public function getOrderDayList() {
        $member_id = $_GET['memberID'];
        $monthBegan = date("Y-m-d", strtotime(trim($_GET['month'])));
        $monthEnd = date("Y-m-d", strtotime('+1months', strtotime(trim($_GET['month']))) - 86400);
        $condition = array();
        $condition['member_id'] = $member_id;
        $condition['order_date'] = array('between', $monthBegan . ',' . $monthEnd);
        $list = M("order")->where($condition)->select();
        $orderList = array();
        if (!empty($list)) {
            foreach ($list as $order) {
                $itemInfo = getItemInfo($order['item_id']);
                $order['item_name'] = $itemInfo['item_name'];
                $order['unit_name'] = $itemInfo['unit_name'];
                $order['item_type'] = $itemInfo['item_type'];
                $order['item_id'] = $itemInfo['item_id'];
                $orderList[$order['order_date']]['list'][] = $order;
            }
            foreach ($orderList as $k => $order) {
                $total = 0;
                foreach ($order['list'] as $orderItem) {
                    $total += $orderItem['pre_price'] * $orderItem['item_number'];
                }
                $orderList[$k]['total'] = $total;
            }
        }
        returnJson(true, $orderList, '');
    }

    public function getOrderInfo() {
        $member_id = $_GET['memberID'];
        $condition = array();
        $condition['member_id'] = $member_id;
        $memberInfo = M("member")->where($condition)->find();
        $canteenInfo = M("canteen")->where(array('canteen_id' => $memberInfo['canteen_id']))->find();
        $condition['order_date'] = date("Y-m-d", strtotime(trim($_GET['month'])));
        $list = M("order")->where($condition)->select();
        foreach ($list as $k => $item) {
            $itemInfo = getItemInfo($item['item_id']);
            $list[$k]['item_name'] = $itemInfo['item_name'];
            $list[$k]['number'] = $item['item_number'];
            $list[$k]['index'] = $item['item_id'];
            $list[$k]['unit_name'] = $itemInfo['unit_name'];
            $list[$k]['item_id'] = $item['item_id'];
            $list[$k]['memo'] = $item['memo'];
            $list[$k]['window_name'] = $memberInfo['window_name'];
            $list[$k]['canteen_name'] = $canteenInfo['canteen_name'];
        }
        returnJson(true, $list, '');
    }

    public function SaveOrder() {
        $member_id = intval($_POST['memberID']);
        $memberInfo = M("member")->where(array('member_id' => $member_id))->find();
        if ($memberInfo['window_status'] == 0) {
            returnJson(false, array(), '保存订单失败，原因「您的账号已被禁用」如有疑问请联系食堂供应商');
        }
        $selectList = $_POST['selectItem'];
        $todayDate = date("Y-m-d", time());
        if (checkCanSave() != true) {
            returnJson(false, array(), '限定提交订单时间已过');
        }
        if (count($selectList) == 0) {
            returnJson(false, array(), '请选择至少一个菜品');
        }
        M("order")->where(array('member_id' => $member_id, 'order_date' => $todayDate))->delete();
        foreach ($selectList as $select) {
            $order = array();
            $order['member_id'] = $member_id;
            $order['order_date'] = $todayDate;
            $order['item_id'] = $select['item_id'];
            $order['item_number'] = !$select['number']==true?0:$select['number'];
            $order['memo'] = $select['memo'];
            M("order")->add($order);
        }

        returnJson(true, array(), '订单保存成功');
    }

    public function getOrderItemList() {
        $member_id = intval($_GET['memberID']);
        $todayDate = date("Y-m-d", time());
        $condition = array();
        $condition['member_id'] = $member_id;
        $condition['order_date'] = $todayDate;
        $list = M("order")->where($condition)->select();
        if (count($list) == 0) {
            //如果没有今天的，查询上一次的

            unset($condition['order_date']);
            $lastOneOrderItem = M("order")->where($condition)->order("order_date desc")->find();
            if (!empty($lastOneOrderItem)) {
                $condition['order_date'] = $lastOneOrderItem['order_date'];
                $list = M("order")->where($condition)->select();
                $selectItemList = $this->sortItemList($list,true);
                foreach ($selectItemList as $k=>$item){
                    if(!$item['item_number']){
                        $selectItemList[$k]['item_number'] = 0;
                    }
                }
                returnJson(true, $selectItemList);

            }
            else {
                returnJson(false);
            }


        }
        else {
            $selectItemList = $this->sortItemList($list);
            foreach ($selectItemList as $k=>$item){
                if(!$item['item_number']){
                    $selectItemList[$k]['item_number'] = 0;
                }
            }
            returnJson(true, $selectItemList);
        }

    }

    public function getItemTypeList() {
        $itemTypeList = M("item_class")->select();
        returnJson(true, $itemTypeList, '');
    }

    public function init() {
        $itemList = import_excel($_SERVER['DOCUMENT_ROOT'] . '/item.xlsx');
        unset($itemList[1]);
        foreach ($itemList as $litm) {
            if (!$litm[1]) continue;
            $data = array();
            $data['item_type'] = $litm['1'];
            $data['item_name'] = $litm['2'];
            $data['unit_name'] = $litm['3'];
            $data['addtime'] = time();
            M("item")->add($data);
        }
        p($itemList);
        $this->display();

    }

    public function login() {
        $username = trim($_POST['username']);
        $password = trim($_POST['password']);
        $memberInfo = M("member")->where(array('username' => $username))->find();
        if (empty($memberInfo)) {
            returnJson(false, array(), '账号密码错误');
        }
        else {
            if ($memberInfo['window_status'] == 0) {
                returnJson(false, array(), "登陆失败，账号失效");

            }
            $pwd = md5($password . $memberInfo['salt_value']);
            if ($pwd == $memberInfo['password']) {
                $data['memberID'] = $memberInfo['member_id'];
                $data['username'] = $memberInfo['username'];
                $data['last_login_time'] = time();
                $memberUpdate['last_login_time'] = time();
                $memberUpdate['login_times'] = $memberInfo['login_times'] + 1;
                $memberUpdate['member_id'] = $memberInfo['member_id'];
                M("member")->save($memberUpdate);
                returnJson(true, $data, "登陆成功");
            }
            else {
                returnJson(false, array(), '账号密码错误');

            }
        }
    }

    public function admin() {
        if (IS_POST) {
            // 做一个简单的登录 组合where数组条件 
            $map = I('post.');
            $map['password'] = md5($map['password']);
            $data = M('Users')->where($map)->find();
            if (empty($data)) {
                $this->error('账号或密码错误');
            }
            else {
                $_SESSION['user'] = array('id' => $data['id'], 'username' => $data['username'], 'avatar' => $data['avatar']);
                $this->success('登录成功、前往管理后台', U('Admin/Index/index'));
            }
        }
        else {
            $data = check_login() ? $_SESSION['user']['username'] . '已登录' : '未登录';
            $assign = array('data' => $data);
            $this->assign($assign);
            $this->display();
        }
    }

    /**
     * 退出
     */
    public function logout() {
        session('user', null);
        $this->success('退出成功、前往登录页面', U('Home/Index/admin'));
    }

    /**
     * 发送邮件
     */
    public function send_email() {
        $email = I('post.email');
        if ($email == 'baijunyao@baijunyao.com') {
            die('请修改邮箱地址已接收测试邮件');
        }
        $result = send_email($email, '邮件标题', '邮件内容');
        if ($result['error'] == 1) {
            p($result);
            die;
        }
        $this->success('发送完成', U('Home/Index/index'));
    }

    /**
     * 生成二维码
     */
    public function qrcode() {
        $url = I('post.url');
        qrcode($url);
    }

    /**
     * 生成pdf
     */
    public function pdf() {
        $content = $_POST['content'];
        pdf($content);
    }

    /**
     * 支付宝
     */
    public function alipay() {
        $price = I('post.price');
        $data = array('out_trade_no' => time(), 'price' => $price, 'subject' => '测试');
        alipay($data);
    }

    /**
     * 微信 公众号jssdk支付
     */
    public function weixinpay_js() {
        // 此处根据实际业务情况生成订单 然后拿着订单去支付

        // 用时间戳虚拟一个订单号  （请根据实际业务更改）
        $out_trade_no = time();
        // 组合url
        $url = U('Api/Weixinpay/pay', array('out_trade_no' => $out_trade_no));
        // 前往支付
        redirect($url);
    }

    /**
     * 微信 扫描支付
     */
    public function weixinpay_qrcode() {
        // 此处根据实际业务情况生成订单 然后拿着订单去支付

        // 虚拟的订单 请根据实际业务更改
        $time = time();
        $order = array('body' => 'test', 'total_fee' => 1, 'out_trade_no' => strval($time), 'product_id' => 1);
        weixinpay($order);
    }

    /**
     * 融云用户1
     */
    public function user1() {
        // 模拟id为89的用户的登录过程
        $user_data = M('Users')->field('id,username,avatar')->find(88);
        $_SESSION['user'] = array('id' => $user_data['id'], 'username' => $user_data['username'], 'avatar' => $user_data['avatar']);
        // 获取融云key
        $rong_key_secret = get_rong_key_secret();
        $assign = array('uid' => $user_data['id'], // 用户id
            'avatar' => $user_data['avatar'],// 头像
            'username' => $user_data['username'],// 用户名
            'rong_key' => $rong_key_secret['key'],// 融云key
            'rong_token' => get_rongcloud_token($user_data['id'])//获取融云token
        );
        $this->assign($assign);
        $this->display();
    }

    /**
     * 融云用户2
     */
    public function user2() {
        // 模拟id为89的用户的登录过程
        $user_data = M('Users')->field('id,username,avatar')->find(89);
        $_SESSION['user'] = array('id' => $user_data['id'], 'username' => $user_data['username'], 'avatar' => $user_data['avatar']);
        // 获取融云key
        $rong_key_secret = get_rong_key_secret();
        $assign = array('uid' => $user_data['id'], // 用户id
            'avatar' => $user_data['avatar'],// 头像
            'username' => $user_data['username'],// 用户名
            'rong_key' => $rong_key_secret['key'],// 融云key
            'rong_token' => get_rongcloud_token($user_data['id'])//获取融云token
        );
        $this->assign($assign);
        $this->display();
    }

    /**
     * 生成xls格式的表格
     */
    public function xls() {
        $data = I('post.data');
        create_xls($data);
    }

    /**
     * 生成csv格式的表格
     */
    public function csv() {
        $data = I('post.data');
        array_walk($data, function (&$v) {
            $v = implode(',', $v);
        });
        create_csv($data);
    }

    /**
     * 导入xls格式的数据
     * 也可以用来导入csv格式的数据
     * 但是csv建议使用 下面的import_csv 效率更高
     */
    public function import_xls() {
        $data = import_excel('./Upload/excel/simple.xls');
        p($data);
    }

    /**
     * 导入csv格式的数据
     */
    public function import_csv() {
        $data = file_get_contents('./Upload/excel/simple.csv');
        $data = explode("\r\n", $data);
        p($data);
    }

    /**
     * geetest生成验证码
     */
    public function geetest_show_verify() {
        $geetest_id = C('GEETEST_ID');
        $geetest_key = C('GEETEST_KEY');
        $geetest = new \Org\Xb\Geetest($geetest_id, $geetest_key);
        $user_id = "test";
        $status = $geetest->pre_process($user_id);
        $_SESSION['geetest'] = array('gtserver' => $status, 'user_id' => $user_id);
        echo $geetest->get_response_str();
    }

    /**
     * geetest submit 提交验证
     */
    public function geetest_submit_check() {
        $data = I('post.');
        if (geetest_chcek_verify($data)) {
            echo '验证成功';
        }
        else {
            echo '验证失败';
        }
    }

    /**
     * geetest ajax 验证
     */
    public function geetest_ajax_check() {
        $data = I('post.');
        echo intval(geetest_chcek_verify($data));
    }

    /**
     * webuploader 上传文件
     */
    public function ajax_upload() {
        // 根据自己的业务调整上传路径、允许的格式、文件大小
        ajax_upload('/Upload/image/');
    }

    /**
     * webuploader 上传demo
     */
    public function webuploader() {
        // 如果是post提交则显示上传的文件 否则显示上传页面
        if (IS_POST) {
            p($_POST);
            die;
        }
        else {
            $this->display();
        }
    }

    /**
     * 用来做测试用
     */
    public function handleImages() {
        $itemList = M("item")->select();
        foreach ($itemList as $item) {
            if (!$item['item_image']) continue;
            $image = new \Think\Image();
            $fileName = $_SERVER['DOCUMENT_ROOT'] . '/Public/images/' . $item['item_image'];
            $fileNamell = explode("/", $item['item_image']);
            $fileNamell = explode(".", $fileNamell[1]);
            $fileNamell = $fileNamell[0];
            $finder = explode('/', $item['item_image']);
            $finder = $finder[0];
            $sadasdFileName = $_SERVER['DOCUMENT_ROOT'] . '/Public/images/' . $finder . "/" . $fileNamell . "_s.jpeg";
            $image->open($fileName);
            $image->thumb(150, 150)->save($sadasdFileName);
        }

    }

    private function sortItemList($itemList,$reset=false) {
        foreach ($itemList as $k => $order) {
            $itemInfo = getItemInfo($order['item_id']);
            $selectItemList[$k]['item_name'] = $itemInfo['item_name'];
            if($reset==true){
                $selectItemList[$k]['number'] = 0;
            }else{
                $selectItemList[$k]['number'] = $order['item_number'];
            }

            $selectItemList[$k]['index'] = $order['item_id'];
            $selectItemList[$k]['unit_name'] = $itemInfo['unit_name'];
            $selectItemList[$k]['item_image'] = $itemInfo['item_image'] ? $itemInfo['item_image'] : 'null.jpg';
            $selectItemList[$k]['item_id'] = $order['item_id'];
            $selectItemList[$k]['check'] = true;
            $selectItemList[$k]['memo'] = $order['memo'];
        }
        return $selectItemList;
    }


}

